package com.newbsd.web.maventest.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.newbsd.web.maventest.pojo.User;
import com.newbsd.web.maventest.service.impl.LoginServiceImpl;



/**
 * @author 张成玉-LoginServlet
 * Servlet implementation class UserServlet
 */
//@WebServlet("/UserServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// TODO Auto-generated method stub
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String authcode = request.getParameter("code");
		
		HttpSession session = request.getSession();
		String code = (String)session.getAttribute("authCode");
		// 验证码识别
		if(!authcode.equals(code)){
//			request.setAttribute("errormsg2", "验证码错误");
			//张成玉-调用万能网页跳转类
//			HttpUtil.forward(request, response, "login.jsp");
			response.getWriter().write("验证码错误");
			return;
		}
		// 登录验证
		// dao<-service<-servlet
		LoginServiceImpl loginService = new LoginServiceImpl();
		User user = loginService.login(username,password);
		if (user == null) {
//			// 返回登录失败
//			request.setAttribute("errormsg", "用户名或密码错误");
			response.getWriter().write("用户名或密码错误");
			return;
//			HttpUtil.forward(request, response, "login.jsp");
		}else {
			// 返回登录成功
			session.setAttribute("user", user);
			request.getSession().setAttribute("loginInfo", user.getRealname());//张成玉-用户真实姓名
			request.getSession().setAttribute("rule", user.getRule());//张成玉用户权限判断
			response.getWriter().write("success");//张成玉-ajax直接在页面输出内容用于字符串匹配
			//request.getRequestDispatcher("User/Index.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
